package com.bootdo.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.*;
import com.bootdo.market.common.HistoryTodayRedis;
import com.bootdo.market.dao.CommonDao;
import com.bootdo.market.dao.DuplicateDao;
import com.bootdo.market.domain.AcommonDO;
import com.bootdo.market.domain.ProductAdvertisementDO;
import com.bootdo.market.domain.ProductAdvpositionDO;
import com.bootdo.market.service.ProductAdvertisementService;
import com.bootdo.market.service.ProductAdvpositionService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jinse
 * @email market@jinse.com
 * @date 2019-04-19 17:45:07
 */

@Controller
@RequestMapping("/market/productAdvertisement")
public class ProductAdvertisementController {
    @Autowired
    private ProductAdvertisementService productAdvertisementService;
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private HistoryTodayRedis historyTodayRedis;
    @Autowired
    private DuplicateDao duplicateDao;
    @Autowired
    private ProductAdvpositionService productAdvpositionService;

    @GetMapping()
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    String ProductAdvertisement() {
        return "market/productAdvertisement/productChannel";
    }

    @ResponseBody
    @GetMapping("/productChannelList")
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    public PageUtils productChannelList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductAdvertisementDO> productAdvertisementList = productAdvertisementService.productChannelList(query);
        int total = productAdvertisementService.productChannelListCount(query);
        PageUtils pageUtils = new PageUtils(productAdvertisementList, total);
        return pageUtils;
    }

    @GetMapping("/productAdvpositionJsp")
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    String productAdvpositionJsp(ProductAdvertisementDO productAdvertisement, Model model) {
        model.addAttribute("productid", productAdvertisement.getProductid());
        model.addAttribute("channelid", productAdvertisement.getChannelid());
        return "market/productAdvertisement/productAdvpositionList";
    }

    @ResponseBody
    @GetMapping("/productAdvpositionList")
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    public PageUtils productAdvpositionList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductAdvertisementDO> productAdvertisementList = productAdvertisementService.productAdvpositionList(query);
        int total = productAdvertisementService.productAdvpositionListCount(query);
        PageUtils pageUtils = new PageUtils(productAdvertisementList, total);
        return pageUtils;
    }

    @GetMapping("/productAdvertisement")
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    String productAdvertisement(ProductAdvertisementDO productAdvertisement, Model model) {
        model.addAttribute("channelid", productAdvertisement.getChannelid());
        model.addAttribute("advpositionid", productAdvertisement.getAdvpositionid());
        model.addAttribute("productid", productAdvertisement.getProductid());
        model.addAttribute("advpositiontype", productAdvertisement.getAdvpositiontype());
        return "market/productAdvertisement/productAdvertisement";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("market:productAdvertisement:productAdvertisement")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductAdvertisementDO> productAdvertisementList = productAdvertisementService.list(query);
        if (productAdvertisementList.size() > 0) {
            productAdvertisementList.forEach(item -> {
                if (item.getAdvimgurl() != null && !"".equals(item.getAdvimgurl())) {
                    item.setAdvimgurl("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + item.getAdvimgurl());
                }
            });
        }
        int total = productAdvertisementService.count(query);
        PageUtils pageUtils = new PageUtils(productAdvertisementList, total);
        return pageUtils;
    }


    @RequestMapping(value = "/JudgingUnique", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R JudgingUnique(HttpServletRequest request, ProductAdvertisementDO productAdvertisement) {
      /*  if (productAdvertisement.getAdvpositiontype() == 4) {
            ProductAdvertisementDO aa = productAdvertisementService.findValidData(productAdvertisement);
            if (aa == null) {
                return R.ok();
            } else {
                return R.error();
            }
        }*/
        return R.ok();
    }

    @GetMapping("/add")
    @RequiresPermissions("market:productAdvertisement:add")
    String add(ProductAdvertisementDO productAdvertisement, Model model) {
        ProductAdvertisementDO dataShow = productAdvertisementService.getDataShow(productAdvertisement);
        model.addAttribute("productAdvertisement", dataShow);
        return "market/productAdvertisement/add";
    }

    @RequestMapping(value = "/getSettlingAccounts", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getSettlingAccounts(HttpServletRequest request) {
        String[] settlingAccounts = AcommonDO.settlingAccounts;
        return JSON.toJSONString(settlingAccounts);
    }

    @RequestMapping(value = "/getVaildChannel", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getVaildChannel(HttpServletRequest request) {
        List<Map<String, Object>> list = commonDao.getVaildChannel();
        return JSON.toJSONString(list);
    }

    @RequestMapping(value = "/getVaildProduct", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getVaildProduct(HttpServletRequest request, ProductAdvertisementDO productAdvertisement) {
        List<Map<String, Object>> list = commonDao.getVaildProduct(productAdvertisement.getChannelid());
        return JSON.toJSONString(list);
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:productAdvertisement:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ProductAdvertisementDO productAdvertisement = productAdvertisementService.get(id);
        List<Map<String, String>> aa = productAdvertisementService.findAreaByOfferId(id);
        List<Map<String, Object>> bb = new ArrayList<>();

        aa.stream().forEach(a -> {
            Map<String, Object> map = new HashMap<>();
            map.put("bigarea", a.get("parent"));
            String ss = a.get("area");
            if (ss == null || "".equals(ss)) {
                map.put("info", "");
            } else {
                String[] strignArray = ss.split(",");
                List<Map<String, String>> arealist = new ArrayList<>();
                for (int i = 0; i < strignArray.length; i++) {
                    Map<String, String> mm = new HashMap<>();
                    mm.put("city", strignArray[i]);
                    arealist.add(mm);
                }
                map.put("info", arealist);
            }
            bb.add(map);
        });
        productAdvertisement.setEdareas(JSON.toJSONString(bb));
        String fileUrl = null, fileName = null;
        if (productAdvertisement.getAdvimgurl() != null && !"".equals(productAdvertisement.getAdvimgurl())) {
            if (productAdvertisement.getAdvimgurl().contains(OssConstant.OSS_FILE_HOST_HISTORY_TODAY)) {
                fileName = productAdvertisement.getAdvimgurl().substring(OssConstant.OSS_FILE_HOST_HISTORY_TODAY.length() + 1);
                fileUrl = productAdvertisement.getAdvimgurl();
            }
            productAdvertisement.setAdvimgurl("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + productAdvertisement.getAdvimgurl());
        }
        model.addAttribute("fileUrl", fileUrl);
        model.addAttribute("fileName", fileName);
        model.addAttribute("productAdvertisement", productAdvertisement);
        return "market/productAdvertisement/edit";
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/");
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(path, filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.uploadFile(newFile, OssConstant.OSS_ENDPOINT_HISTORY_TODAY, OssConstant.OSS_BUCKETNAME_HISTORY_TODAY, OssConstant.OSS_FILE_HOST_HISTORY_TODAY);
                    if (StringUtils.isNotBlank(uploadUrl)) {
                        return newFile.getName() + "#" + uploadUrl + "#" + "http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + uploadUrl;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return null;
    }

    /**
     * 保存
     */
    @Transactional
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("market:productAdvertisement:add")
    public R save(ProductAdvertisementDO productAdvertisement) {
        String json = "";
        if (!StringUtils.isEmpty(productAdvertisement.getEdareas())) {
            if (!productAdvertisement.getEdareas().startsWith("[")) {
                json = "{\"data\":[" + productAdvertisement.getEdareas() + "]}";
            } else {
                json = "{\"data\":" + productAdvertisement.getEdareas() + "}";
            }
            if ("[]".equals(productAdvertisement.getEdareas())) {
                productAdvertisement.setIsdirectional(0);
            } else {
                productAdvertisement.setIsdirectional(1);
            }
        } else {
            productAdvertisement.setIsdirectional(0);
        }
        if (productAdvertisement.getAdvnum() == null) {
            productAdvertisement.setAdvnum(-1);
        }
        //生成JS静态文件代码
        if (productAdvertisement.getIsgeneratefiles() == 1) {
            String str = "";
            String tempStr = "";
            try {
                InputStream in = this.getClass().getResourceAsStream("/adjs.html");
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                while ((tempStr = br.readLine()) != null) {
                    str = str + tempStr;
                }
                in.close();
                //替换掉模块中相应的地方
                str = str.replaceAll("###content###", productAdvertisement.getAdvjs());
                String uuid = String.valueOf(UUID.random(0, 10) + System.currentTimeMillis());
                String fileUrl = "/app/nnjr-web/web-file/" + DateUtil.getCurrentDate() + File.separator + uuid + ".html";
                File f = new File(fileUrl);
                File fileParent = f.getParentFile();
                if (!fileParent.exists()) {
                    fileParent.mkdirs();
                }
                f.createNewFile();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
                bufferedWriter.write(str);
                bufferedWriter.newLine();//换行
                bufferedWriter.flush();
                bufferedWriter.close();
                System.out.println("-----------------------" + fileUrl);
                productAdvertisement.setAdvJsPathUrl("/web-file/" + DateUtil.getCurrentDate() + File.separator + uuid + ".html");
               /* //上传到OSS
                String uploadUrl = AliyunOSSUtil.uploadFile(f, OssConstant.OSS_ENDPOINT_HISTORY_TODAY, OssConstant.OSS_BUCKETNAME_HISTORY_TODAY, OssConstant.OSS_FILE_JSADFRAMEFILEHOST);
                if (StringUtils.isNotBlank(uploadUrl)) {
                    System.out.println("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + uploadUrl);
                    productAdvertisement.setAdvJsPathUrl(uploadUrl);
                }*/
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            productAdvertisement.setAdvJsPathUrl(null);
        }
        //保存广告
        productAdvertisementService.save(productAdvertisement);
        List<String> listCity = new ArrayList<>();
        if (!StringUtils.isEmpty(productAdvertisement.getEdareas())) {
            JSONObject areaObject = JSON.parseObject(json);
            com.alibaba.fastjson.JSONArray areaArray = areaObject.getJSONArray("data");
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (int i = 0; i < areaArray.size(); i++) {
                JSONObject object = areaArray.getJSONObject(i);
                if (object.get("info") == null || "".equals(object.get("info"))) {
                    Map<String, Object> areas = new HashMap<>();
                    areas.put("offer_id", productAdvertisement.getId());
                    areas.put("parent_area", object.getString("bigarea"));
                    areas.put("area", "");
                    mapList.add(areas);
                    listCity.add(object.getString("bigarea"));
                } else {
                    com.alibaba.fastjson.JSONArray array = object.getJSONArray("info");
                    for (int j = 0; j < array.size(); j++) {
                        Map<String, Object> areas = new HashMap<>();
                        areas.put("offer_id", productAdvertisement.getId());
                        areas.put("parent_area", object.getString("bigarea"));
                        areas.put("area", array.getJSONObject(j).getString("city"));
                        mapList.add(areas);
                        listCity.add(array.getJSONObject(j).getString("city"));
                    }
                }
            }
            if (mapList.size() > 0) {
                productAdvertisementService.insertOfferArea(mapList);
            }
        }
        ProductAdvertisementDO aaaa = productAdvertisementService.get(productAdvertisement.getId());
        //todo 更新进入redis
        updateAdvertisementDataIntoRedis(aaaa);
    /*    if (aaaa.getIsdelete() == 1 && aaaa.getPublishstate() == 1) {
            if (aaaa.getIsdirectional() == 1) {
                List<String> aa = commonDao.findAreaIntoRedisOfferId(aaaa.getId());
                aaaa.setEdareas(JSON.toJSONString(aa));
            } else {
                List<String> aa = new ArrayList<>();
                aaaa.setEdareas(JSON.toJSONString(aa));
            }
            historyTodayRedis.saveProductAdvertisementRedis(aaaa);
        } else {
            historyTodayRedis.deleteProductAdvertisementRedis(aaaa);
        }*/
        return R.ok();
    }

    /**
     * 将文章信息更新进入redis
     */
    void updateAdvertisementDataIntoRedis(ProductAdvertisementDO aaaa) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<ProductAdvertisementDO> advertisementList = commonDao.listProductAdvertisement(aaaa);
        if (advertisementList != null && advertisementList.size() > 0) {
            advertisementList.stream().forEach(productAdvertisementDO -> {

                if (productAdvertisementDO.getIsdirectional() == 1) {
                    List<String> aa = commonDao.findAreaIntoRedisOfferId(productAdvertisementDO.getId());
                    productAdvertisementDO.setEdareas(JSON.toJSONString(aa));
                } else {
                    List<String> aa = new ArrayList<>();
                    productAdvertisementDO.setEdareas(JSON.toJSONString(aa));
                }
                Map<String, Object> map = new HashMap<>();
                map.put("id", productAdvertisementDO.getId() == null ? "" : productAdvertisementDO.getId());
                map.put("productId", productAdvertisementDO.getProductid() == null ? "" : productAdvertisementDO.getProductid());
                map.put("advertiserName", productAdvertisementDO.getAdvertisername() == null ? "" : productAdvertisementDO.getAdvertisername());
                map.put("advEvent", productAdvertisementDO.getAdvevent() == null ? "" : productAdvertisementDO.getAdvevent());
                map.put("advDes", productAdvertisementDO.getAdvdes() == null ? "" : productAdvertisementDO.getAdvdes());
                map.put("advType", productAdvertisementDO.getAdvtype() == null ? "" : productAdvertisementDO.getAdvtype());
                map.put("advName", productAdvertisementDO.getAdvname() == null ? "" : productAdvertisementDO.getAdvname());
                map.put("advImgUrl", productAdvertisementDO.getAdvimgurl() == null ? "" : productAdvertisementDO.getAdvimgurl());
                map.put("advUrl", productAdvertisementDO.getAdvurl() == null ? "" : productAdvertisementDO.getAdvurl());
                map.put("advJs", productAdvertisementDO.getAdvjs() == null ? "" : productAdvertisementDO.getAdvjs());
                map.put("advJsPathUrl", productAdvertisementDO.getAdvJsPathUrl() == null ? "" : productAdvertisementDO.getAdvJsPathUrl());
/*
        map.put("advNum", productAdvertisementDO.getAdvnum() == null ? "" : productAdvertisementDO.getAdvnum());
*/
                map.put("isDirectional", productAdvertisementDO.getIsdirectional() == null ? "" : productAdvertisementDO.getIsdirectional());
                map.put("area", productAdvertisementDO.getEdareas() == null ? "" : productAdvertisementDO.getEdareas());
                map.put("advContent", productAdvertisementDO.getAdvcontent() == null ? "" : productAdvertisementDO.getAdvcontent());
                map.put("advDescription", productAdvertisementDO.getAdvDescription() == null ? "" : productAdvertisementDO.getAdvDescription());
                map.put("settlementPosition", productAdvertisementDO.getSettlementposition() == null ? "" : productAdvertisementDO.getSettlementposition());
                map.put("settlementW", productAdvertisementDO.getSettlementw() == null ? "" : productAdvertisementDO.getSettlementw());
                map.put("settlementH", productAdvertisementDO.getSettlementh() == null ? "" : productAdvertisementDO.getSettlementh());
                map.put("advSort", productAdvertisementDO.getAdvsort() == null ? "" : productAdvertisementDO.getAdvsort());
                mapList.add(map);
                historyTodayRedis.saveProductAdvertisementRedis(mapList, aaaa);

            });
        } else {
            historyTodayRedis.deleteProductAdvertisementRedis(aaaa);

        }

    }

    /**
     * 修改
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("market:productAdvertisement:edit")
    public R update(ProductAdvertisementDO productAdvertisement) {
        String json = "";
        if (!StringUtils.isEmpty(productAdvertisement.getEdareas())) {
            if (!productAdvertisement.getEdareas().startsWith("[")) {
                json = "{\"data\":[" + productAdvertisement.getEdareas() + "]}";
            } else {
                json = "{\"data\":" + productAdvertisement.getEdareas() + "}";
            }
            if ("[]".equals(productAdvertisement.getEdareas())) {
                productAdvertisement.setIsdirectional(0);
            } else {
                productAdvertisement.setIsdirectional(1);
            }
        } else {
            productAdvertisement.setIsdirectional(0);
        }
        if (productAdvertisement.getAdvnum() == null) {
            productAdvertisement.setAdvnum(-1);
        }
        //生成JS静态文件代码
        if (productAdvertisement.getIsgeneratefiles() == 1) {
            String str = "";
            String tempStr = "";
            try {
                InputStream in = this.getClass().getResourceAsStream("/adjs.html");
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                while ((tempStr = br.readLine()) != null) {
                    str = str + tempStr;
                }
                in.close();
                //替换掉模块中相应的地方
                str = str.replaceAll("###content###", productAdvertisement.getAdvjs());
                String uuid = String.valueOf(UUID.random(0, 10) + System.currentTimeMillis());
                String fileUrl = "/app/nnjr-web/web-file/" + DateUtil.getCurrentDate() + File.separator + uuid + ".html";
                File f = new File(fileUrl);
                if (!f.getParentFile().exists()) {
                    boolean result = f.getParentFile().mkdirs();
                    if (!result) {
                        System.out.println("创建文件目录失败");
                    } else {
                        f.createNewFile();
                    }
                }
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
                bufferedWriter.write(str);
                bufferedWriter.newLine();//换行
                bufferedWriter.flush();
                bufferedWriter.close();
                System.out.println("-----------------------" + fileUrl);
                productAdvertisement.setAdvJsPathUrl("/web-file/" + DateUtil.getCurrentDate() + File.separator + uuid + ".html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            productAdvertisement.setAdvJsPathUrl(null);
        }
        //todo 先删除redis的这个zset的sort，因为sort会改变
        /*ProductAdvertisementDO bbbb = productAdvertisementService.get(productAdvertisement.getId());
        historyTodayRedis.deleteProductAdvertisementRedis(bbbb);*/

        productAdvertisementService.update(productAdvertisement);
        productAdvertisementService.deleteOfferAreaByOfferId(productAdvertisement.getId());
        List<String> listCity = new ArrayList<>();
        if (!StringUtils.isEmpty(productAdvertisement.getEdareas())) {
            JSONObject areaObject = JSON.parseObject(json);
            com.alibaba.fastjson.JSONArray areaArray = areaObject.getJSONArray("data");
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (int i = 0; i < areaArray.size(); i++) {
                JSONObject object = areaArray.getJSONObject(i);
                if (object.get("info") == null || "".equals(object.get("info"))) {
                    Map<String, Object> areas = new HashMap<>();
                    areas.put("offer_id", productAdvertisement.getId());
                    areas.put("parent_area", object.getString("bigarea"));
                    areas.put("area", "");
                    mapList.add(areas);
                    listCity.add(object.getString("bigarea"));
                } else {
                    com.alibaba.fastjson.JSONArray array = object.getJSONArray("info");
                    for (int j = 0; j < array.size(); j++) {
                        Map<String, Object> areas = new HashMap<>();
                        areas.put("offer_id", productAdvertisement.getId());
                        areas.put("parent_area", object.getString("bigarea"));
                        areas.put("area", array.getJSONObject(j).getString("city"));
                        mapList.add(areas);
                        listCity.add(array.getJSONObject(j).getString("city"));
                    }
                }
            }
            if (mapList.size() > 0) {
                productAdvertisementService.insertOfferArea(mapList);
            }
        }
        ProductAdvertisementDO aaaa = productAdvertisementService.get(productAdvertisement.getId());
        //todo 更新进入redis
        updateAdvertisementDataIntoRedis(aaaa);
       /* if (aaaa.getIsdelete() == 1 && aaaa.getPublishstate() == 1) {
            if (aaaa.getIsdirectional() == 1) {
                List<String> aa = commonDao.findAreaIntoRedisOfferId(aaaa.getId());
                aaaa.setEdareas(JSON.toJSONString(aa));
            } else {
                List<String> aa = new ArrayList<>();
                aaaa.setEdareas(JSON.toJSONString(aa));
            }
            historyTodayRedis.saveProductAdvertisementRedis(aaaa);
        } else {
            historyTodayRedis.deleteProductAdvertisementRedis(aaaa);
        }*/
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("market:productAdvertisement:remove")
    public R remove(ProductAdvertisementDO productAdvertisement) {
        productAdvertisementService.update(productAdvertisement);
        ProductAdvertisementDO aaaa = productAdvertisementService.get(productAdvertisement.getId());
        //todo 更新进入redis
        updateAdvertisementDataIntoRedis(aaaa);

        /*    if (aaaa.getIsdelete() == 1 && aaaa.getPublishstate() == 1) {
            if (aaaa.getIsdirectional() == 1) {
                List<String> aa = commonDao.findAreaIntoRedisOfferId(aaaa.getId());
                aaaa.setEdareas(JSON.toJSONString(aa));
            } else {
                List<String> aa = new ArrayList<>();
                aaaa.setEdareas(JSON.toJSONString(aa));
            }
            historyTodayRedis.saveProductAdvertisementRedis(aaaa);
        } else {
            historyTodayRedis.deleteProductAdvertisementRedis(aaaa);
        }*/
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("market:productAdvertisement:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            ProductAdvertisementDO productTags = new ProductAdvertisementDO();
            productTags.setId(ids[i]);
            productTags.setPublishstate(1);
            productAdvertisementService.update(productTags);
            ProductAdvertisementDO aaaa = productAdvertisementService.get(ids[i]);
            //todo 更新进入redis
            updateAdvertisementDataIntoRedis(aaaa);
          /*  if (aaaa.getIsdelete() == 1 && aaaa.getPublishstate() == 1) {
                if (aaaa.getIsdirectional() == 1) {
                    List<String> aa = commonDao.findAreaIntoRedisOfferId(aaaa.getId());
                    aaaa.setEdareas(JSON.toJSONString(aa));
                } else {
                    List<String> aa = new ArrayList<>();
                    aaaa.setEdareas(JSON.toJSONString(aa));
                }
                historyTodayRedis.saveProductAdvertisementRedis(aaaa);
            } else {
                historyTodayRedis.deleteProductAdvertisementRedis(aaaa);
            }*/
        }
        return R.ok();
    }

    @RequestMapping(value = "/productAdvertisementUniqueAdd", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R productAdvertisementUniqueAdd(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.productAdvertisementUniqueAdd(params);
        if (aa == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping(value = "/productAdvertisementUniqueEdit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R productAdvertisementUniqueEdit(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.productAdvertisementUniqueEdit(params);
        if (aa == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 删除
     */
    @GetMapping("/batchredis")
    @ResponseBody
    @RequiresPermissions("market:productAdvertisement:batchredis")
    public R batchredis() {

        //todo 初始化广告位
        List<ProductAdvpositionDO> Advpositionlist = commonDao.batchRedisGetAllProductAdvposition();
        if (Advpositionlist != null && Advpositionlist.size() > 0) {
            for (int i = 0; i < Advpositionlist.size(); i++) {
                ProductAdvpositionDO aaa = productAdvpositionService.get(Advpositionlist.get(i).getId());
                if (aaa.getIsdelete() == 1) {
                    historyTodayRedis.saveAdvpositionConfigRedis(aaa);
                } else {
                    historyTodayRedis.deleteAdvpositionConfigRedis(aaa);
                }
            }
        }

        //todo 初始化广告
        List<ProductAdvertisementDO> list = commonDao.batchRedisGetAllProductAdvertisement();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ProductAdvertisementDO aaaa = productAdvertisementService.get(list.get(i).getId());
                //todo 更新进入redis
                updateAdvertisementDataIntoRedis(aaaa);
                /*   if (aaaa.getIsdelete() == 1 && aaaa.getPublishstate() == 1) {
                    if (aaaa.getIsdirectional() == 1) {
                        List<String> aa = commonDao.findAreaIntoRedisOfferId(aaaa.getId());
                        aaaa.setEdareas(JSON.toJSONString(aa));
                    } else {
                        List<String> aa = new ArrayList<>();
                        aaaa.setEdareas(JSON.toJSONString(aa));
                    }
                    historyTodayRedis.saveProductAdvertisementRedis(aaaa);
                } else {
                    historyTodayRedis.deleteProductAdvertisementRedis(aaaa);
                }*/
            }
        }


        return R.ok();
    }
}
